package com.rc.common.advice;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotRoleException;
import com.rc.common.constant.Code;
import com.rc.common.exception.BusinessException;
import com.rc.common.util.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

/**
 * 公共异常捕捉
 */
@RestControllerAdvice
//@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class CommonExceptionAdvice {

    /**
     * 参数校验异常处理
     * @param e
     * @return
     */
    @ExceptionHandler({BindException.class})
    public R methodArgNotValidExceptionHandler(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        //如果不为空则遍历msg
        bindingResult.getFieldErrors()
                .forEach(error -> sb.append(error.getField())
                            .append(error.getDefaultMessage())
                            .append(", 当前值: '")
                            .append(error.getRejectedValue())
                        .append("'"));
        Integer code = Code.ARG_VALID_ERROR.getCode();
        String msg = sb.toString();
        return R.fail(code, msg);
    }

    @ExceptionHandler({ConstraintViolationException.class})
    public R constraintViolationExceptionr(ConstraintViolationException e) {
        Integer code = Code.ARG_VALID_ERROR.getCode();
        return R.fail(code, e.getLocalizedMessage());
    }


    /**
     * 业务异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    public R businessExceptionHandler(BusinessException e) {
        return R.fail(e.getCode(), e.getMessage());
    }

    /**
     * 未登录
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    public R ex(){
        return R.fail(Code.NO_LOGIN);
    }

    /**
     * 角色异常
     * @return
     */
    @ExceptionHandler(NotRoleException.class)
    public R notRoleException(NotRoleException e){
        return R.fail(Code.ROLE_ERROR);
    }

    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {
        e.printStackTrace();
        return R.fail(Code.SERVER_ERROR);
    }
}
